﻿using System;
using System.Collections.Generic;
using System.IO;

namespace dk.Helper.Base.Core
{
    public class VillageDataReader : IVillageDataReader
    {
        #region IVillageDataReader Members

        /// <summary>
        /// Creates the villages.
        /// </summary>
        /// <param name="datafile">The datafile.</param>
        /// <returns></returns>
        public IVillages CreateVillages(string datafile)
        {
            if (!File.Exists(datafile))
                return null;

            IVillageParser villageParser = new VillageParser();
            IVillages villages = new Villages();
            using (TextReader textReader = new StreamReader(datafile))
            {
                string data;
                while ((data = textReader.ReadLine()) != null)
                {
                    IVillage village = villageParser.CreateVillage(data);
                    if (village == null)
                    {
                        throw new InvalidOperationException("Failed to parse village: " + data);
                    }
                    villages.VillagesByCoord[village.Coord.X, village.Coord.Y] = village;
                    villages.VillagesByID.Add(village.ID, village);
                    if (!villages.VillagesByPlayerID.ContainsKey(village.PlayerID))
                        villages.VillagesByPlayerID.Add(village.PlayerID, new List<IVillage>());
                    if (!villages.VillagesByPlayerID[village.PlayerID].Contains(village))
                        villages.VillagesByPlayerID[village.PlayerID].Add(village);
                }
            }
            return villages;
        }

        #endregion
    }
}